package com.leadcloud.nim.login;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leadcloud.nim.CommonCache;
import com.leadcloud.nim.NimApplication;
import com.netease.nim.uikit.common.MyConst;
import com.leadcloud.nim.config.preference.Preferences;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFrame;
import com.netease.nim.uikit.common.http.NimHttpClient;
import com.netease.nim.uikit.common.leadbean.SentenceBean;
import com.netease.nim.uikit.common.util.log.LogUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wujiankun on 2018/4/13.
 *
 */

public class WsManager {
    private static WsManager mInstance;
    private final String TAG = this.getClass().getSimpleName();

    /**
     * WebSocket config
     */
    private static final int FRAME_QUEUE_SIZE = 5;
    private static final int CONNECT_TIMEOUT = 10000;
    private static String MSG_URL = "wss://testwebsocket.leadscloud.com/websocketLeavemessage/websocket/";
    private static String CHAT_URL = "wss://testwebsocket.leadscloud.com/websocket/websocket/";

    private WsStatus mStatus;
    private WebSocket ws_msg;
    private WebSocket ws_chat;

    private WsManager() {
    }

    public static WsManager getInstance() {
        if (mInstance == null) {
            synchronized (WsManager.class) {
                if (mInstance == null) {
                    mInstance = new WsManager();
                }
            }
        }
        return mInstance;
    }

    public void init() {
        LogUtil.i(TAG, "WsManager init:"+new Date().toString());
        /*try {
            String msgUrl = MSG_URL + Preferences.getOrgId() + '/' + Preferences.getUserId();
            String charUrl = CHAT_URL + Preferences.getOrgId() + '/' + Preferences.getUserAccount();
            ws_chat = new WebSocketFactory().createSocket(charUrl, CONNECT_TIMEOUT)
                    //.setFrameQueueSize(FRAME_QUEUE_SIZE)//设置帧队列最大值为5
                    //.setMissingCloseFrameAllowed(false)//设置不允许服务端关闭连接却未发送关闭帧
                    .addListener(new WsListener("chat"))//添加回调监听
                    .connectAsynchronously();//异步连接

            ws_msg = new WebSocketFactory().createSocket(msgUrl, CONNECT_TIMEOUT)
                    //.setFrameQueueSize(FRAME_QUEUE_SIZE)//设置帧队列最大值为5
                    //.setMissingCloseFrameAllowed(false)//设置不允许服务端关闭连接却未发送关闭帧
                    .addListener(new WsListener("msg"))//添加回调监听
                    .connectAsynchronously();//异步连接
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        NimHttpClient.getInstance().init(CommonCache.getContext());
        String userType = Preferences.getString("userType");
        if(userType!=null&&userType.equals("1")){
            //设置客服在状态为在线
           Map<String, String> headers = new HashMap<>(1);
            /* String body = "?accid" + "=" + Preferences.getUserAccount() + "&operateSource=android_app_login&onlineFlag=1";
            NimHttpClient.getInstance().execute(MyConst.FIX_ONLINE_STATE_URL + body, headers, body,
                    false, new NimHttpClient.NimHttpCallback() {
                        @Override
                        public void onResponse(String response, int code, Throwable exception) {
                        }
                    });*/
            //拿取话术列表和语言列表
            NimHttpClient.getInstance().execute(MyConst.ALL_LANGUAGE_LIST, headers, "", false,
                    new NimHttpClient.NimHttpCallback() {
                        @Override
                        public void onResponse(String response, int code, Throwable exception) {
                            if (code != 200 || exception != null) {
                            } else {
                                JSONObject parse = JSONObject.parseObject(response);
                                JSONObject data = parse.getJSONObject("data");
                                String dataString = data.getString("languages");
                                Preferences.saveString("language", dataString);
                            }
                        }
                    });

            String orgId = Preferences.getOrgId();
            String url = MyConst.GET_SENTENCE_URL;
            if(null!=orgId){
                url = url+"?orgId="+orgId;
            }
            NimHttpClient.getInstance().execute(url , headers, "", false,
                    new NimHttpClient.NimHttpCallback() {
                        @Override
                        public void onResponse(String response, int code, Throwable exception) {
                            if (code != 200 || exception != null) {
                            }else{
                                JSONObject parse = JSONObject.parseObject(response);
                                String data = parse.getString("data");
                                Preferences.saveString("sentence",data);
                            }
                        }
                    });
        }
    }


    /**
     * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
     * onTextMessage 收到文字信息
     * onConnected 连接成功
     * onConnectError 连接失败
     * onDisconnected 连接关闭
     */
    public class WsListener extends WebSocketAdapter {
        String type;

        WsListener(String type) {
            this.type = type;
        }

        @Override
        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            super.onTextMessage(websocket, text);
            LogUtil.i(TAG, text);
            if ("msg".equals(type)) {
                LogUtil.i(TAG, "收到留言信息 from socket");
            }
        }


        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
                throws Exception {
            super.onConnected(websocket, headers);
            setStatus(WsStatus.CONNECT_SUCCESS);
            if ("msg".equals(type)) {
                LogUtil.i(TAG, "留言信息socket连接成功");
                startTimerTask();
            } else if ("chat".equals(type)) {
                LogUtil.i(TAG, "聊天状态socket连接成功");
            }
        }

        private Timer timer;

        private void startTimerTask() {
            if(timer==null){
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        sendPing();
                    }
                }, 3000, 60*1000);
            }
        }


        @Override
        public void onConnectError(WebSocket websocket, WebSocketException exception)
                throws Exception {
            super.onConnectError(websocket, exception);
            LogUtil.i(TAG, "连接错误"+exception.getMessage());
            setStatus(WsStatus.CONNECT_FAIL);
        }


        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
                throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            LogUtil.i(TAG, "断开连接");
            setStatus(WsStatus.CONNECT_FAIL);
            if(timer!=null){
                timer.cancel();timer=null;
            }
        }
    }

    private void setStatus(WsStatus status) {
        this.mStatus = status;
    }

    public WsStatus getStatus() {
        return mStatus;
    }

    public void disconnect() {
        if (ws_chat != null)
            ws_chat.disconnect();
        if (ws_msg != null)
            ws_msg.disconnect();
    }

    public void sendPing() {
        if (ws_chat != null && ws_chat.isOpen()) {
            ws_chat.sendPing();
            LogUtil.i(TAG, "Websocket_chat send ping " + new Date().toString());
        }

        if (ws_msg != null && ws_msg.isOpen()) {
            ws_msg.sendPing();
            LogUtil.i(TAG, "Websocket_msg send ping " + new Date().toString());
        }

    }

    public enum WsStatus {
        CONNECT_SUCCESS,//连接成功
        CONNECT_FAIL,//连接失败
        CONNECTING;//正在连接
    }
}
